<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>

        <el-col :span="24">
          <el-form-item :label="$t('申请标题')" prop="actTitle">
            <el-input v-model="form.actTitle" :placeholder="$t('申请标题')" show-word-limit maxlength="50" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="$t('承租人名称')" prop="lesseeId">
            <template>
              <router-link
                target="_blank"
                :to="{path:'/company/base/companyBaseHome',query:{companyId:form.lesseeId}}"
                class="link_a"
              >{{ form.lesseeName }}
              </router-link>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('项目名称')" prop="dealName">
            <template>
              <router-link
                target="_blank"
                :to="{path:'/deal/home/dealBaseHome',query:{id:form.dealId}}"
                class="link_a"
              >{{ form.dealName }}
              </router-link>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('交易模式')" prop="transactionMode">
            <dict-select
              v-model="form.transactionMode"
              dictionary="deal_lease_transaction_mode"
              :placeholder="$t('交易模式')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('客户联系人')" prop="customerContact">
            <el-input v-model="form.customerContact" :placeholder="$t('客户联系人')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('合同总额')+$t('金额单位')" prop="totalContractAmount">
            <Money v-model="form.totalContractAmount" :placeholder="$t('合同总额')" unit="w" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('合同编号')" prop="contractNo">
            <el-input v-model="form.contractNo" :placeholder="$t('合同编号')" show-word-limit maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('租金总额')+$t('金额单位')" prop="totalRent">
            <Money v-model="form.totalRent" :placeholder="$t('租金总额')" unit="w" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('租赁利率(%)')" prop="leaseRate">
            <Ratio
              v-model="form.leaseRate"
              :precision="4"
              :controls="false"
              :min="0"
              :max="100"
              :placeholder="$t('租赁利率(%)')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('税率(%)')" prop="taxRate">
            <Ratio
              v-model="form.taxRate"
              :precision="4"
              :controls="false"
              :min="0"
              :max="100"
              :placeholder="$t('税率(%)')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('XIRR(%)')" prop="xirr">
            <Ratio
              v-model="form.xirr"
              :precision="4"
              :controls="false"
              :min="0"
              :max="100"
              :placeholder="$t('XIRR(%)')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('手续费/咨询费')+$t('金额单位')" prop="serviceCharge">
            <Money v-model="form.serviceCharge" :placeholder="$t('手续费/咨询费')" unit="w" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('保证金')+$t('金额单位')" prop="earnestMoney">
            <Money v-model="form.earnestMoney" :placeholder="$t('保证金')" unit="w" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('起租日')" prop="commencementDate">
            <el-date-picker
              v-model="form.commencementDate"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('起租日')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('到期日')" prop="expiringDate">
            <el-date-picker
              v-model="form.expiringDate"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('到期日')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('期限（月）')" prop="term">
            <el-input v-model="form.term" :placeholder="$t('期限（月）')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('担保人')" prop="guarantee">
            <el-input v-model="form.guarantee" :placeholder="$t('担保人')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('担保方式')" prop="guaranteeMethod">
            <el-input v-model="form.guaranteeMethod" :placeholder="$t('担保方式')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('其他担保方式')" prop="otherGuaranteeMethod">
            <el-input v-model="form.otherGuaranteeMethod" :placeholder="$t('其他担保方式')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" type="textarea" :placeholder="$t('备注')" show-word-limit maxlength="1000" />
          </el-form-item>
        </el-col>
      </el-row>
      <FileTable :list.sync="form.fileList" has-permi="financing:contract" data-type="deal_lease_contract" :business-id="form.dealId" :btn-show="!otherBtnHide" />
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <FormBtn ref="formBtn" :bus-data="form" has-permi="financing:contract" />
    </div>
  </div>
</template>

<script>
import {
  saveDealLeaseContract,
  getDealLeaseContract,
  monthlyCalculation
} from '@/api/deal/financing/contract/dealLeaseContract'
    import { getDealBase } from '@/api/base/deal/dealBase'
    export default {
        data() {
            return {
                // 表单参数
                form: {},
                // 表单校验
                rules: {
                  actTitle: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  transactionMode: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  customerContact: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  totalContractAmount: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  contractNo: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  totalRent: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  leaseRate: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  taxRate: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  xirr: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  serviceCharge: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  earnestMoney: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  commencementDate: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  expiringDate: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  term: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  guarantee: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  guaranteeMethod: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]

                },
                // 遮罩层
                loading: false,
                // 操作按钮默认不展示
                buttonShow: true,
                // 是否隐藏其它按钮
                otherBtnHide: false
            }
        },
      watch: {
        'form.commencementDate': {
          handler(newValue) {
            if (newValue !== '' && newValue !== undefined) {
              this.monthlyCalculation(this.form)
            }
          },
          immediate: true
        },
        'form.expiringDate': {
          handler(newValue) {
            if (newValue !== '' && newValue !== undefined) {
              this.monthlyCalculation(this.form)
            }
          },
          immediate: true
        }
      },
        created() {
            this.getDicts('financing_transaction_mode').then(response => {
                this.transactionModeOptions = response.data
            })
            this.$bus.$emit('async_done')
        },
        methods: {
            // 初始化数据
            init(data) {
                this.loading = true
                if (data != null && data.id !== undefined) {
                    getDealLeaseContract(data.id).then(response => {
                        this.form = response.data
                        this.loading = false
                    }).catch(() => {
                        this.loading = false
                    })
                } else {
                    this.reset()
                    getDealBase(this.$route.query.id).then(response => {
                      this.form.dealName = response.data.dealName
                      this.form.lesseeId = response.data.companyId
                      this.form.lesseeName = response.data.company.companyName
                      this.form.transactionMode = response.data.dealBaseLease.transactionMode
                      this.form.leaseRate = response.data.dealBaseLease.leaseRate
                      this.form.xirr = response.data.dealBaseLease.xirr
                      this.form.serviceCharge = response.data.dealBaseLease.serviceCharge
                      this.form.earnestMoney = response.data.dealBaseLease.bond
                      this.form.guarantee = response.data.dealBaseLease.guaranteeSubject
                      this.form.guaranteeMethod = response.data.dealBaseLease.guaranteeMethod
                      this.form.otherGuaranteeMethod = response.data.dealBaseLease.otherGuaranteeMethods
                      this.loading = false
                    }).catch(() => {
                      this.loading = false
                    })
                    this.loading = false
                }
            },
            // 表单重置
            reset() {
                this.form = {
                    id: undefined,
                    dealId: this.$route.query.id,
                    actTitle: undefined,
                    actId: undefined,
                    actStatus: undefined,
                    lesseeId: undefined,
                    lesseeName: undefined,
                    dealName: undefined,
                    transactionMode: undefined,
                    customerContact: undefined,
                    totalContractAmount: undefined,
                    contractNo: undefined,
                    totalRent: undefined,
                    leaseRate: undefined,
                    taxRate: undefined,
                    xirr: undefined,
                    serviceCharge: undefined,
                    earnestMoney: undefined,
                    commencementDate: undefined,
                    expiringDate: undefined,
                    term: undefined,
                    guarantee: undefined,
                    guaranteeMethod: undefined,
                    otherGuaranteeMethod: undefined,
                    remark: undefined,
                    createBy: undefined,
                    createTime: undefined,
                    updateBy: undefined,
                    updateTime: undefined,
                    delFlag: undefined
                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                if (this.$parent.$parent.formOpen !== undefined) {
                    this.$parent.$parent.formOpen = false
                }
                // 刷新list页面
                if (this.$parent.$parent.getList !== undefined) {
                  this.$parent.$parent.getList()
                }
            },
            /** 提交按钮 */
            submitForm(type) {
                return new Promise((resolve, reject) => {
                  this.$refs['form'].validate(valid => {
                    // 验证数据
                    if (valid) {
                      // 弹出遮罩层
                      this.loading = true
                      // 保存数据
                      saveDealLeaseContract(this.form).then(response => {
                        if (response.code === 200) {
                          // 点击的按钮是保存并启动流程
                          if (type === 'process') {
                            // 启动流程
                            this.startProcess(response.data)
                            // 点击的仅保存
                          } else {
                            this.msgSuccess(this.$t('保存成功'))
                            // 关闭form页面
                            this.closeForm()
                          }
                          resolve()
                        } else {
                          this.msgError(response.msg)
                          this.loading = false
                          reject()
                        }
                      })
                    } else {
                      reject()
                      this.locationError(document)
                    }
                  })
                }).catch(() => {
                    this.loading = false
                })
           },
            // 启动流程
           startProcess(data) {
               this.loading = false
               // 启动流程时候传入的参数
               const processData = {}
               // 待办标题
               processData.title = '[' + data.dealName + ']' + data.actTitle
               // 业务表名
               processData.dataTable = 'deal_lease_contract'
               // 业务ID
               processData.dataId = data.id
               // 业务表单地址(待办页面需要打开的页面)
               processData.formPath = '@/views/deal/financing/contract/dealLeaseContractForm'
               // 菜单标识(根据菜单标识判断的走哪个流程)
               processData.menuKey = 'deal_lease_contract'
               this.startProcessByMenu(processData, () => {
                   this.form.actStatus = 'D'
                   this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
                   this.closeForm()
               })
           },
          // 期限计算
          monthlyCalculation(data) {
            monthlyCalculation(data).then(response => {
              console.log(response.data)
              this.form.term = response.data.term
            })
          }

        }

    }
</script>
